<!-- 添加/编辑 资产 -->

<template>
  <DialogLayout ref="dialogRef" method="POST" path="/dev-api/oa/headcount" @submited="handlerDialogSubmited">
    <el-form-item label="资产名称" prop="name">
      <el-input v-model="dialogForm.name" autocomplete="off" />
    </el-form-item>
    <el-form-item label="部门" prop="deptIds">
      <el-cascader :options="deptList" :props="deptProps" v-model="dialogForm.deptIds" style="width: 100%" @change="handleChangeDept" />
    </el-form-item>
    <el-form-item label="用户" prop="userId">
      <el-select v-model="dialogForm.userId" filterable clearable reserve-keyword placeholder="" @change="handlerChangeTeacher" :loading="loading" style="width: 100%">
        <el-option v-for="item in teacherOptions" :key="item.userId" :label="item.nickName + '-' + item.userName" :value="item.userId" />
      </el-select>
    </el-form-item>
    <el-form-item label="编码" prop="code">
      <el-input v-model="dialogForm.code" autocomplete="off" />
    </el-form-item>
    <el-form-item label="资产类型" prop="assetCategory">
      <el-select v-model="dialogForm.assetCategory" clearable>
        <el-option class="radio-option-cell" v-for="(item, idx) in useAssetCategoryStore().assetCategory" :key="idx" :value="item.dictValue" :label="item.dictLabel" />
      </el-select>
    </el-form-item>
    <el-form-item label="状态" prop="assetStatus">
      <el-radio-group v-model="dialogForm.assetStatus">
        <el-radio-button v-for="(item, idx) in useAssetStatusStore().assetStatus" :key="idx" :value="item.dictValue" :label="item.dictLabel" />
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="dialogForm.remark" autocomplete="off" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" placeholder="" />
    </el-form-item>
  </DialogLayout>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import DialogLayout from '../../layout/DialogLayout.vue'
import { FormRules } from 'element-plus'
import { useDeptStore, useAssetCategoryStore, useAssetStatusStore } from '../../stores'
import { ElMessage } from 'element-plus'
import api from '../../api'

const emits = defineEmits(['submited'])
const deptProps = ref({ label: 'deptName', value: 'deptId' })
const deptList = ref(useDeptStore().getAllState())
const dialogRef = ref<InstanceType<typeof DialogLayout>>()
const teacherOptions = ref<any[]>([])
const loading = ref(false)
// const userList = ref<any[]>([])

const dialogForm = reactive({
  id: null,
  name: '',
  code: '',
  userId: null,
  userName: '',
  userNick: '',
  assetCategory: null,
  deptIds: [] as number[],
  deptId: null as any,
  deptName: '',
  assetStatus: null,
  remark: '',
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入资产名称', trigger: ['blur', 'change'] }],
  deptIds: [{ required: true, message: '请选择部门', trigger: ['blur', 'change'] }],
  code: [{ required: true, message: '请输入资产编码', trigger: ['blur', 'change'] }],
  assetCategory: [{ required: true, message: '请选择资产类型', trigger: ['blur', 'change'] }],
  assetStatus: [{ required: true, message: '请选择资产状态', trigger: ['blur', 'change'] }],
  userId: [{ required: true, message: '请选择用户', trigger: ['blur', 'change'] }],
})

const openDialog = async (val: any) => {
  let dialogTitle = '添加资产'
  if (val.id) {
    dialogTitle = '编辑资产'
    dialogForm.id = val.id
    dialogForm.name = val.name
    dialogForm.code = val.code
    dialogForm.userId = val.userId
    dialogForm.userName = val.userName
    dialogForm.userNick = val.userNick
    dialogForm.assetCategory = val.assetCategory.toString()
    dialogForm.deptId = val.deptId
    dialogForm.deptName = val.deptName
    dialogForm.assetStatus = val.assetStatus.toString()
    dialogForm.remark = val.remark

    const deptItem = useDeptStore().deptList.find((item: any) => item.deptId === dialogForm.deptId)
    // console.log('openDialog deptItem', deptItem.ancestors, dialogForm.deptId)
    dialogForm.deptIds = [...deptItem.ancestors.split(',').map(Number), dialogForm.deptId].filter((item) => item !== 0)
    await getUserList(dialogForm.deptIds[dialogForm.deptIds.length - 1])
    // teacherOptions.value.unshift({ userId: dialogForm.userId, userName: dialogForm.userName, nickName: dialogForm.userNick })
  } else {
    dialogForm.id = null
    dialogForm.name = ''
    dialogForm.code = ''
    dialogForm.userId = null
    dialogForm.userName = ''
    dialogForm.userNick = ''
    dialogForm.assetCategory = null
    dialogForm.deptId = null
    dialogForm.deptName = ''
    dialogForm.assetStatus = null
    dialogForm.remark = ''
    dialogForm.deptIds = []
  }
  dialogRef.value?.openDialog({
    title: dialogTitle,
    class: 'dialog-add-training',
    form: dialogForm,
    rules: rules,
    submitFunction: async (callback: Function) => {
      // buildParams(1, 2)
      dialogForm.deptId = dialogForm.deptIds[dialogForm.deptIds.length - 1]
      const deptItem = useDeptStore().deptList.find((item: any) => item.deptId === dialogForm.deptId)
      dialogForm.deptName = deptItem.deptName
      // console.log('submitFunction 2 dialogForm', { ...dialogForm })

      let res: any = null
      let messageText = ''
      if (dialogForm.id) {
        res = await api.Asset.update({ ...dialogForm })
        messageText = '修改'
      } else {
        res = await api.Asset.add({ ...dialogForm })
        messageText = '添加'
      }
      console.log('submitFunction  res', res)
      if (res.code == 200) {
        ElMessage({
          message: `${messageText}成功！`,
          grouping: true,
          type: 'success',
        })
      } else {
        ElMessage({
          message: `${messageText}失败！`,
          grouping: true,
          type: 'error',
        })
      }
      emits('submited')
      await callback()
    },
  })
}

/**
 * 处理对话框提交事件
 *
 * @param data 提交的数据
 */
const handlerDialogSubmited = () => {
  // emits('submited', data)

  dialogForm.id = null
  dialogForm.name = ''
  dialogForm.code = ''
  dialogForm.userId = null
  dialogForm.userName = ''
  dialogForm.userNick = ''
  dialogForm.assetCategory = null
  dialogForm.deptId = null
  dialogForm.deptName = ''
  dialogForm.assetStatus = null
  dialogForm.remark = ''
  dialogForm.deptIds = []
}

// const remoteMethod = async (query: string) => {
//   loading.value = true
//   if (query) {
//     setTimeout(() => {
//       teacherOptions.value = userList.value.filter((item: any) => {
//         return item.userName.toLowerCase().includes(query.toLowerCase())
//       })
//       loading.value = false
//     }, 200)
//   } else {
//     teacherOptions.value = []
//   }
// }

/**
 * 处理部门选择变化
 *
 * @param value 当前选中的部门值
 */
const handleChangeDept = async (value: any) => {
  dialogForm.userId = null
  teacherOptions.value = []
  await getUserList(value[value.length - 1])
}

const getUserList = async (deptId: number | null = 0) => {
  const params = {
    pageSize: 999999,
  }
  if (deptId && deptId > 0) {
    Object.assign(params, { deptId })
  }
  teacherOptions.value = await api.Users.getAll(params)
}

const handlerChangeTeacher = async (value: any) => {
  teacherOptions.value.find((item: any) => {
    if (item.userId === value) {
      dialogForm.userId = item.userId
      dialogForm.userName = item.userName
      dialogForm.userNick = item.nickName
    }
  })
  // console.log('handlerChangeTeacher', dialogForm)
}
defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped>
.radio-option-cell {
  margin-bottom: 10px;
  margin-right: 10px;
}
</style>
